/*
 * Copyright (C) 2013 Daniel Wasilew <daniel.wasilew@codeminer.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.codeminer.parts.update;

import org.apache.commons.io.IOUtils;
import org.codeminer.parts.application.ApplicationContext;
import org.codeminer.parts.settings.Settings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

/**
 *
 * @author Daniel Wasilew <daniel.wasilew@codeminer.org>
 */
public class HttpVersionFetcher implements AvailableVersionFetcher {

    private static final Logger log = LoggerFactory.getLogger(HttpVersionFetcher.class);
    private final ApplicationContext applicationContext;

    public HttpVersionFetcher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public Version getAvailableVersion() {
        Settings settings = this.applicationContext.getApplicationPart(Settings.class);
        URL url = settings.getUpdateVersionInfoURL();
        if (url != null) {
            InputStream httpStream = null;
            try {
                httpStream = url.openStream();
                Properties updateVersion = new Properties();
                updateVersion.load(httpStream);
                String version = updateVersion.getProperty("version");
                long buildId = Long.parseLong(updateVersion.getProperty("buildId", "-1"));
                String buildTime = updateVersion.getProperty("buildTime");
                return Version.custom(version, buildId, buildTime);
            } catch (IOException ex) {
                log.debug("could not open connection to [" + url + "]", ex);
            } finally {
                if (httpStream != null) {
                    try {
                        httpStream.close();
                    } catch (IOException ex) {
                        log.trace("could not close stream", ex);
                    }
                }
            }
        }
        return Version.NO_UPDATE;
    }

    @Override
    public UpdateInformation fetchUpdate() throws UpdateException {
        Settings settings = this.applicationContext.getApplicationPart(Settings.class);
        URL url = settings.getUpdatePackageURL();
        
        if (url != null) {
            InputStream httpStream = null;
            FileOutputStream fos = null;
            try {
                File outputFile = new File(applicationContext.getTmpDir(), settings.getUpdatePackageLocation());
                if (outputFile.exists()) {
                    outputFile.delete();
                }
                log.trace("downloading [{}] to [{}]", url.getPath(), outputFile.getAbsolutePath());
                httpStream = url.openStream();
                fos = new FileOutputStream(outputFile);
                
                IOUtils.copy(httpStream, fos);
                
                return new PartsUpdateInformation(outputFile, applicationContext);
                
            } catch (IOException ex) {
                log.error("could not open connection to [" + url + "]", ex);
            } finally {
                IOUtils.closeQuietly(httpStream);
                IOUtils.closeQuietly(fos);
            }
        }
        throw new UpdateException();
    }
}
